// miniprogram/packageUser/pages/edit-record/edit-record.js
import {getStorageSync} from "../../../utils/Storage"
import {addRecord, getRecordDetail, updateRecord} from "../../../service/Record"
import Toast from "@vant/weapp/toast/toast";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageShow: false,
        isHasDetail: false,
        loading: false,
        formData: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this._options = options;
        this.getRecordDetail(options.id)
    },

    /*
    * 获取详情信息
    * */
    getRecordDetail: async function (id) {
        try {
            Toast.loading({
                mask: true,
                message: "加载中...",
            });
            let detail = await getRecordDetail(id) || {};
            if (detail.type === "lost") {
                this.setData({
                    formData: {
                        type: detail.type,
                        name: detail.name,
                        intro: detail.intro,
                        phone: detail.phone,
                        images: detail.images.map(function (item) {
                            return {id: item, url: item}
                        }),
                        time: detail.time,
                        region: detail.region,
                        regionDetail: detail.regionDetail
                    },
                    isHasDetail: true
                })
            } else {
                this.setData({
                    formData: {
                        type: detail.type,
                        images: detail.images.map(function (item) {
                            return {id: item, url: item}
                        }),
                        intro: detail.intro,
                        phone: detail.phone,
                        region: detail.region,
                        regionDetail: detail.regionDetail
                    },
                    isHasDetail: true
                })
            }
        } catch (e) {
            this.setData({isHasDetail: false});
            console.error(e)
        } finally {
            Toast.clear();
            this.setData({pageShow: true});
        }
    },

    /*
    * 监听丢失发布数据
    * */
    onUpdateRecord: async function (e) {
        try {
            await updateRecord(this._options.id, e.detail);
            this.setData({loading: false})
            Toast.success({
                message: "更新成功",
                mask: true,
                onClose: () => {
                    wx.navigateBack()
                }
            });
        } catch (e) {
            this.setData({loading: false})
            Toast.fail("发布失败");
            console.error(e)
        }
    }

})